package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //加密后会得到一个16进制字符串

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //检查状态是否可用
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        //1，要将接受过来的DTO数据封装到Entity中
        Employee employee = new Employee();
        //原始方式将dto数据一个个设置到entity非常低效
        //BeanUtils可以用来做对象属性的拷贝
        BeanUtils.copyProperties(employeeDTO,employee);

        //2,完善employee中属性：默认密码，状态，创建，更新时间，创建，更新的用户
        //默认密码
        String mdgPwd = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(mdgPwd);
        //状态
        employee.setStatus(StatusConstant.ENABLE);
        //创建时间
      /*  LocalDateTime now = LocalDateTime.now();
        employee.setCreateTime(now);
        //修改时间
        employee.setUpdateTime(now);

        //创建用户
        //Ctrl+Alt+V : 抽取表达式为局部变量
        //从线程局部变量中获取empId
        Long currentId = BaseContext.getCurrentId();
        employee.setCreateUser(currentId);
        //修改用户
        employee.setUpdateUser(currentId);*/

        //3 调用mapper层，把employee插入到数据库中
        employeeMapper.insert(employee);

    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        //封装PageResult
        if (page.getResult().size()==0) {
            throw new NoDataException(MessageConstant.NO_DATA);
        }
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        //修改员工的状态，构建表的实体映射对象 Employee
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .build();
        //调用mapper层去更新
        employeeMapper.update(employee);
    }

    @Override
    public Employee getById(Long id) {
        //调用mapper查询指定id的员工数据
        Employee employee = employeeMapper.getById(id);
        //为了安全起见，需要把密码替换成无意义的字符串
        employee.setPassword("************");
        return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        //把DTO转换为实体对象,并填充数据
        //DTO中，更新时间，更新用户
        Employee employee = Employee.builder()
//                .updateTime(LocalDateTime.now())
//                .updateUser(BaseContext.getCurrentId())
                .build();
        //将DTO数据填充到employee中
        BeanUtils.copyProperties(employeeDTO,employee);
        //调用mapper实现更新
        employeeMapper.update(employee);
    }

}
